﻿using Colder.Logging.Serilog;
using EFCore.Sharding;
using FieldTools.Api;
using FieldTools.Util;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System.Threading;

namespace FieldTools.Client.HttpServer
{
    /// <summary>
    /// host服务
    /// </summary>
    public class MyHttpServer
    {
        /// <summary>
        /// 运行服务
        /// </summary>
        /// <param name="cts"></param>
        public static void RunServer(CancellationToken cts)
        {
            //cts.ThrowIfCancellationRequested();
            try
            {
                Host.CreateDefaultBuilder()
                .ConfigureLoggingDefaults()
                .UseIdHelper()
                .UseCache()
                .ConfigureServices((hostContext, services) =>
                {
                    services.AddMemoryCache();
                    services.AddFxServices();
                    services.AddAutoMapper();
                    services.AddEFCoreSharding(config =>
                    {
                        config.SetEntityAssemblies(GlobalAssemblies.AllAssemblies);

                        var dbOptions = hostContext.Configuration.GetSection("Database:BaseDb").Get<DatabaseOptions>();

                        config.UseDatabase(dbOptions.ConnectionString, dbOptions.DatabaseType);
                    });
                })
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                })
                //.RunConsoleAsync(cts);
                .Build()
                .RunAsync(cts);
            }
            catch (System.Exception ex)
            {
                cts.ThrowIfCancellationRequested();
                //throw;
            }

        }
    }
}
